package com.hxd.otc.widget;

import android.graphics.Paint;
import android.os.Build;
import android.text.TextUtils;
import android.view.ViewTreeObserver;
import android.widget.TextView;

/**
 * Created by lzy on 2018/9/13 0013.
 * description ${用于TextView正确换行的布局监听}
 */
public class AutoSplitOnTvGlobalLayoutAdapter implements ViewTreeObserver.OnGlobalLayoutListener {

    private TextView mTextView;

    public AutoSplitOnTvGlobalLayoutAdapter(TextView textView) {
        mTextView = textView;
    }

    @Override
    public void onGlobalLayout() {
        if (mTextView == null) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } else {
            mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        final String newText = autoSplitText(mTextView);
        if (!TextUtils.isEmpty(newText)) {
            mTextView.setText(newText);
        }
        mTextView = null;//避免内存泄露
    }

    /**
     * 复用时可以重置
     *
     * @param textView
     */
    public void resetTextView(TextView textView) {
        mTextView = textView;
    }

    private String autoSplitText(final TextView tv) {
        final String rawText = tv.getText().toString(); //原始文本
        final Paint tvPaint = tv.getPaint(); //paint，包含字体等信息
        final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度

        //将原始文本按行拆分
        String[] rawTextLines = rawText.replaceAll("\r", "").split("\n");
        StringBuilder sbNewText = new StringBuilder();
        for (String rawTextLine : rawTextLines) {
            if (tvPaint.measureText(rawTextLine) <= tvWidth) {
                //如果整行宽度在控件可用宽度之内，就不处理了
                sbNewText.append(rawTextLine);
            } else {
                //如果整行宽度超过控件可用宽度，则按字符测量，在超过可用宽度的前一个字符处手动换行
                float lineWidth = 0;
                for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
                    char ch = rawTextLine.charAt(cnt);
                    lineWidth += tvPaint.measureText(String.valueOf(ch));
                    if (lineWidth <= tvWidth) {
                        sbNewText.append(ch);
                    } else {
                        sbNewText.append("\n");
                        lineWidth = 0;
                        --cnt;
                    }
                }
            }
            sbNewText.append("\n");
        }

        //把结尾多余的\n去掉
        if (!rawText.endsWith("\n")) {
            sbNewText.deleteCharAt(sbNewText.length() - 1);
        }

        return sbNewText.toString();
    }
}